package user.view;



import java.util.ArrayList;
import java.util.Calendar;

import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import javax.swing.border.EmptyBorder;
import javax.swing.JList;
import javax.swing.JComboBox;

import db.Booking;
import db.CitiesManager;
import db.FlightsManage;
import db.UserValidate;

import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JScrollPane;

import javax.swing.JTextField;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

import user.model.UserModel;

public class UserMain extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7257543259380624071L;
	private JPanel contentPane;
	private boolean isvistor;
	private DefaultListModel defaultListModel;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	private JTextField textField_4;
	private JTextField textField_5;
	private JTextField textField_6;
	private JTextField textField_7;
	private Vector<String[]> flightsArrayList;
	private ArrayList<String[]> citiesArrayList;
	private JComboBox month_comboBox;
	private JComboBox date_comboBox;
	private JComboBox year_comboBox;
	private JList list;
	private JComboBox from_combo;
	private JComboBox to_comboBox;
	private JComboBox num_comboBox;
	private JTextField textField_8;
	private static UserMain inst;
	private JMenu mnAccount;
	private JLabel result_label;
	private JButton btnSubmit;
	private JButton searchByCity_btn;
	private JButton button;
	private JButton btnSearch;

	/**
	 * Launch the application.
	 */
	public static UserMain getInstance() {
		if (inst == null)
			inst = new UserMain();
		return inst;
	}

	public void setToVisitorModel() {
		mnAccount.setEnabled(false);
		isvistor = true;
	}

	/**
	 * Create the frame.
	 */
	private UserMain() {
		
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				UserValidate.setExit();
				System.exit(0);
			}
		});
		setTitle("User panel");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 737, 501);
		{
			JMenuBar menuBar = new JMenuBar();
			setJMenuBar(menuBar);
			{
				mnAccount = new JMenu("Account");
				menuBar.add(mnAccount);
				{
					JMenuItem editmenu = new JMenuItem("Profile");
					editmenu.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							UserEditFrame.getInstance().setVisible(true);
						}
					});
					mnAccount.add(editmenu);
				}
				{
					JMenuItem mntmDeleteAccount = new JMenuItem(
							"Delete Account");
					mntmDeleteAccount.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							int r = JOptionPane.showConfirmDialog(UserMain
									.getInstance(),
									"Are you sure to delete your account?");
							if (JOptionPane.OK_OPTION == r) {
								int rs = UserValidate.deleteAccount(LoginView
										.getInstance().getUsername());
								if (1 == rs) {
									System.exit(0);
								} else
									JOptionPane.showMessageDialog(UserMain
											.getInstance(), "system error");

							}
						}
					});
					mnAccount.add(mntmDeleteAccount);
				}
				{
					JMenuItem mntmHistory = new JMenuItem("History");
					mntmHistory.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							UserHistoryFrame.getInstance().setVisible(true);
						}
					});
					mnAccount.add(mntmHistory);
				}
			}
		}
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		{
			defaultListModel = new DefaultListModel();
		}
		contentPane.setLayout(null);
		{
			from_combo = new JComboBox();
			from_combo.setBounds(111, 56, 72, 21);
			addCities(from_combo);
			contentPane.add(from_combo);
		}
		{
			to_comboBox = new JComboBox();
			to_comboBox.setBounds(111, 104, 72, 21);
			addCities(to_comboBox);
			contentPane.add(to_comboBox);
		}
		{
			JLabel lblDestination = new JLabel("Destination");
			lblDestination.setBounds(22, 107, 79, 15);
			contentPane.add(lblDestination);
		}
		{
			JLabel lblDeparture = new JLabel("Departure");
			lblDeparture.setBounds(22, 59, 79, 15);
			contentPane.add(lblDeparture);
		}
		{
			JLabel lblDepartureDate = new JLabel("Departure date");
			lblDepartureDate.setBounds(47, 194, 96, 15);
			contentPane.add(lblDepartureDate);
		}
		{
			month_comboBox = new JComboBox();
			month_comboBox.setBounds(115, 219, 72, 21);
			month_comboBox.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {

					changeDays();

				}
			});
			contentPane.add(month_comboBox);
		}
		{
			JLabel lblM = new JLabel("M");
			lblM.setBounds(86, 222, 19, 15);
			contentPane.add(lblM);
		}
		{
			JLabel lblD = new JLabel("D");
			lblD.setBounds(86, 251, 31, 15);
			contentPane.add(lblD);
		}
		{
			date_comboBox = new JComboBox();
			date_comboBox.setBounds(115, 248, 72, 21);
			contentPane.add(date_comboBox);
		}
		{
			JLabel lblY = new JLabel("Y");
			lblY.setBounds(86, 282, 31, 15);
			contentPane.add(lblY);
		}
		{
			year_comboBox = new JComboBox();
			year_comboBox.setBounds(115, 279, 72, 21);
			year_comboBox.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					changeDays();
				}
			});
			contentPane.add(year_comboBox);
		}
		{
			JScrollPane scrollPane = new JScrollPane();
			scrollPane.setBounds(275, 57, 134, 311);
			contentPane.add(scrollPane);
			{
				defaultListModel = new DefaultListModel();
				list = new JList(defaultListModel);
				list.addListSelectionListener(new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent e) {
						// System.out.println(list.getValueIsAdjusting()+" "+
						// list.getSelectedIndex());
						if (list.getValueIsAdjusting()) {
							int s = list.getSelectedIndex();
							textField.setText(flightsArrayList.elementAt(s)[0]);
							textField_1
									.setText(flightsArrayList.elementAt(s)[1]);
							textField_2
									.setText(flightsArrayList.elementAt(s)[2]);
							int sold = Integer.parseInt(flightsArrayList
									.elementAt(s)[9]);
							int total = Integer.parseInt(flightsArrayList
									.elementAt(s)[3]);
							textField_3.setText((total - sold) + "/" + total);
							textField_4
									.setText(flightsArrayList.elementAt(s)[4]);
							int from = Integer.parseInt(flightsArrayList
									.elementAt(s)[6]);
							int to = Integer.parseInt(flightsArrayList
									.elementAt(s)[5]);
							textField_5.setText(getCity(from));
							textField_6.setText(getCity(to));
							textField_7
									.setText(flightsArrayList.elementAt(s)[7]
											+ "% off (>="
											+ flightsArrayList.elementAt(s)[8]
											+ " tickets)");
							textField_8
									.setText(flightsArrayList.elementAt(s)[10]);
							num_comboBox.removeAllItems();
							for (int i = 1; i <= (total - sold); i++)
								num_comboBox.addItem(i);
							result_label.setText("");
						}
					}

				});

				scrollPane.setViewportView(list);

			}
		}
		{
			JLabel lblFlightId = new JLabel("Flight ID");
			lblFlightId.setBounds(430, 54, 72, 15);
			contentPane.add(lblFlightId);
		}
		{
			textField = new JTextField();
			textField.setBounds(532, 51, 133, 21);
			textField.setEditable(false);
			contentPane.add(textField);
			textField.setColumns(10);
		}
		{
			JLabel lblDeparture_1 = new JLabel("Departure");
			lblDeparture_1.setBounds(430, 95, 72, 15);
			contentPane.add(lblDeparture_1);
		}
		{
			textField_1 = new JTextField();
			textField_1.setBounds(532, 95, 133, 21);
			textField_1.setEditable(false);
			contentPane.add(textField_1);
			textField_1.setColumns(10);
		}
		{
			JLabel lblTakeOffTime = new JLabel("Take off time");
			lblTakeOffTime.setBounds(430, 141, 88, 15);
			contentPane.add(lblTakeOffTime);
		}
		{
			textField_2 = new JTextField();
			textField_2.setBounds(532, 138, 133, 21);
			textField_2.setEditable(false);
			contentPane.add(textField_2);
			textField_2.setColumns(10);
		}
		{
			JLabel lblAv = new JLabel("Unsold seats");
			lblAv.setBounds(430, 182, 102, 15);
			contentPane.add(lblAv);
		}
		{
			textField_3 = new JTextField();
			textField_3.setBounds(532, 179, 133, 21);
			textField_3.setEditable(false);
			contentPane.add(textField_3);
			textField_3.setColumns(10);
		}
		{
			JLabel lblPrice = new JLabel("Price($)");
			lblPrice.setBounds(430, 224, 54, 15);
			contentPane.add(lblPrice);
		}
		{
			textField_4 = new JTextField();
			textField_4.setBounds(532, 221, 133, 21);
			textField_4.setEditable(false);
			contentPane.add(textField_4);
			textField_4.setColumns(10);
		}
		{
			JLabel lblFrom = new JLabel("From");
			lblFrom.setBounds(430, 306, 54, 15);
			contentPane.add(lblFrom);
		}
		{
			textField_5 = new JTextField();
			textField_5.setBounds(474, 303, 72, 21);
			textField_5.setEditable(false);
			contentPane.add(textField_5);
			textField_5.setColumns(10);
		}
		{
			JLabel lblTo = new JLabel("To");
			lblTo.setBounds(556, 306, 54, 15);
			lblTo.setEnabled(false);
			contentPane.add(lblTo);
		}
		{
			textField_6 = new JTextField();
			textField_6.setBounds(599, 303, 66, 21);
			textField_6.setEditable(false);
			contentPane.add(textField_6);
			textField_6.setColumns(10);
		}
		{
			JLabel lblDiscount = new JLabel("Discount:");
			lblDiscount.setBounds(430, 353, 72, 15);
			contentPane.add(lblDiscount);
		}
		{
			textField_7 = new JTextField();
			textField_7.setBounds(494, 350, 171, 21);
			textField_7.setEditable(false);
			contentPane.add(textField_7);
			textField_7.setColumns(10);
		}
		{
			searchByCity_btn = new JButton("List");
			searchByCity_btn.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					updateByCities();
				}
			});
			searchByCity_btn.setBounds(193, 103, 72, 23);
			contentPane.add(searchByCity_btn);
		}
		{
			button = new JButton("List");
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					updateByTime();
				}
			});
			button.setBounds(193, 311, 72, 23);
			contentPane.add(button);
		}
		{
			btnSearch = new JButton("Search");
			btnSearch.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					updateByCitiesAndTime();
				}
			});
			btnSearch.setBounds(44, 349, 134, 40);
			contentPane.add(btnSearch);
		}
		{
			JLabel lblBuy = new JLabel("Buy");
			lblBuy.setBounds(430, 392, 54, 15);
			contentPane.add(lblBuy);
		}
		{
			num_comboBox = new JComboBox();
			num_comboBox.setBounds(494, 389, 52, 21);
			contentPane.add(num_comboBox);
		}
		{
			btnSubmit = new JButton("submit");
			btnSubmit.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					submit();
				}
			});
			btnSubmit.setBounds(572, 388, 93, 23);
			contentPane.add(btnSubmit);
		}
		{
			JLabel lblAirportTax = new JLabel("Airport Tax($)");
			lblAirportTax.setBounds(430, 264, 102, 15);
			contentPane.add(lblAirportTax);
		}
		{
			textField_8 = new JTextField();
			textField_8.setEditable(false);
			textField_8.setBounds(532, 261, 134, 21);
			contentPane.add(textField_8);
			textField_8.setColumns(10);
		}
		{
			result_label = new JLabel("");
			result_label.setForeground(Color.GREEN);
			result_label.setBounds(474, 420, 191, 15);
			contentPane.add(result_label);
		}
		
		JButton btnListAllAirlines = new JButton("List all");
		btnListAllAirlines.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				showAll();
			}
		});
		btnListAllAirlines.setBounds(111, 10, 154, 23);
		contentPane.add(btnListAllAirlines);
		initDateCombox();

	}

	private void addCities(JComboBox box) {
		if(citiesArrayList==null)citiesArrayList = CitiesManager.getCities();
		for (String[] strings : citiesArrayList) {
			box.addItem(strings[0]);

		}
	}

	private String getCity(int index) {
		for (String[] n : citiesArrayList) {
			if (n[2].equals(index + ""))
				return n[0];
		}
		return "";
	}

	private void initDateCombox() {
		for (int i = 2009; i < 2020; i++)
			year_comboBox.addItem(i);
		for (int i = 1; i <= 12; i++)
			month_comboBox.addItem(i);
		for (int i = 1; i <= 31; i++)
			date_comboBox.addItem(i);

		Calendar c = Calendar.getInstance();
		System.out.println(c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH)
				+ "-" + c.get(Calendar.DATE));

		year_comboBox.setSelectedIndex(c.get(Calendar.YEAR) - 2009);
		month_comboBox.setSelectedIndex(c.get(Calendar.MONTH));

		date_comboBox.setSelectedIndex(c.get(Calendar.DATE) - 1);

	}

	private void changeDays() {
		date_comboBox.removeAllItems();
		Calendar c = Calendar.getInstance();
		c.set(year_comboBox.getSelectedIndex() + 2009, month_comboBox
				.getSelectedIndex(), 1);

		int days = c.getActualMaximum(Calendar.DAY_OF_MONTH);
		for (int i = 1; i <= days; i++)
			date_comboBox.addItem(i);

		date_comboBox.setSelectedIndex(0);
	}

	private String getTime() {
		StringBuffer sb = new StringBuffer();
		sb.append((year_comboBox.getSelectedIndex() + 2009) + "-");
		sb.append((month_comboBox.getSelectedIndex() + 1) + "-");
		sb.append(date_comboBox.getSelectedIndex() + 1);
		return sb.toString();
	}

	private void updateByTime() {
		defaultListModel.setSize(0);
		flightsArrayList = FlightsManage.getFlightsByDepartureDate(getTime());
		for (String[] str : flightsArrayList) {
			defaultListModel.addElement(str[0]);
		}
	}

	private void updateByCities() {
		defaultListModel.setSize(0);
		flightsArrayList = FlightsManage.getFlightsByCities(to_comboBox
				.getSelectedItem().toString(), from_combo.getSelectedItem()
				.toString());
		for (String[] str : flightsArrayList) {
			defaultListModel.addElement(str[0]);
		}
	}

	private void updateByCitiesAndTime() {
		defaultListModel.setSize(0);
		flightsArrayList = FlightsManage.getFlightsByDepartureDateAndCity(
				getTime(), to_comboBox.getSelectedItem().toString(), from_combo
						.getSelectedItem().toString());
		for (String[] str : flightsArrayList) {
			defaultListModel.addElement(str[0]);
		}
	}
	private void showAll()
	{
		defaultListModel.setSize(0);
		flightsArrayList = FlightsManage.getFlightsForUser();
		for (String[] str : flightsArrayList) {
			defaultListModel.addElement(str[0]);
		}
	}
	private void submit() {
		String userid;
		if (isvistor) {

			userid=JOptionPane.showInputDialog(this, "please input your name");
			if(userid==null||userid.trim().equals(""))return;
			String delivery=JOptionPane.showInputDialog(this,"input the delivery address");
			if(delivery==null||delivery.trim().equals(""))return;
			UserModel um=new UserModel();
			um.setName(userid+"_vistor_"+Math.round(Math.random()*10000));
			um.setAddress(delivery);
			if(0==UserValidate.addUser(um))
				{
					JOptionPane.showMessageDialog(this,"system error ,retry please");
					return;
				};
			
		}else userid= LoginView.getInstance().getUsername();
			
		int r = JOptionPane.showConfirmDialog(UserMain.getInstance(),
					"Are you sure to buy "
							+ (num_comboBox.getSelectedIndex() + 1)
							+ " ticket(s)?");
			if (JOptionPane.OK_OPTION == r) {

			int suc = Booking.buyTickets(Integer.parseInt(textField.getText()), userid,num_comboBox.getSelectedIndex() + 1);
			result_label.setText(suc + " tickets ready for you!");
			}
		
	}
	public void setConnectFailed()
	{
		btnSubmit.setEnabled(false);
		btnSubmit.setText("offline");
		btnSearch.setEnabled(false);
		searchByCity_btn.setEnabled(false);
		button.setEnabled(false);
	}
}
